import { aiService } from '@/utils/ai-service'
import type { ChatMessage } from '@/types/ai-models'

/**
 * 测试最新的三个深度思考/推理模型
 * - Qwen Plus Latest (默认深度思考)  
 * - Doubao Seed 1.6
 * - DeepSeek R1 (推理模型)
 */

// 测试任务列表
const TEST_TASKS = [
  {
    name: '逻辑推理问题',
    prompt: '有三个人：张三说李四撒谎，李四说王五撒谎，王五说张三和李四都撒谎。请分析谁在说真话，谁在撒谎？',
    systemPrompt: '你是一个逻辑推理专家，请仔细分析问题并给出推理过程。'
  },
  {
    name: '数学应用题',
    prompt: '一个水池有两个进水管A和B，一个出水管C。单独开A管需要6小时装满，单独开B管需要4小时装满，单独开C管需要12小时放完。如果三管同时开，多长时间能装满水池？请详细列出计算过程。',
    systemPrompt: '你是一个数学专家，请详细展示解题步骤和推理过程。'
  },
  {
    name: '代码优化问题', 
    prompt: `请优化这段JavaScript代码，提高性能和可维护性：

\`\`\`javascript
function processUsers(users) {
  let result = [];
  for (let i = 0; i < users.length; i++) {
    if (users[i].age > 18 && users[i].active == true) {
      let userData = {
        name: users[i].name,
        email: users[i].email,
        age: users[i].age
      };
      if (users[i].vip) {
        userData.priority = 'high';
      } else {
        userData.priority = 'normal';
      }
      result.push(userData);
    }
  }
  return result;
}
\`\`\`

请给出优化后的代码并解释优化原因。`,
    systemPrompt: '你是一个资深的JavaScript开发专家，注重代码质量和性能优化。'
  },
  {
    name: '创意写作',
    prompt: '以"时间旅行者的困境"为主题，写一个500字左右的科幻小故事，要求有悬念和反转。',
    systemPrompt: '你是一个富有想象力的科幻小说作家。'
  }
]

// 执行单个测试
async function runSingleTest(task: typeof TEST_TASKS[0], provider: string, model: string) {
  console.log(`\n=== ${provider} (${model}) - ${task.name} ===`)
  console.log(`测试问题: ${task.prompt.substring(0, 100)}...`)
  
  const startTime = Date.now()
  
  try {
    const messages: ChatMessage[] = [
      { role: 'system', content: task.systemPrompt },
      { role: 'user', content: task.prompt }
    ]
    
    const response = await aiService.chat(messages, {
      provider,
      model,
      temperature: 0.7,
      maxTokens: 4000
    })
    
    const duration = Date.now() - startTime
    const content = response.choices[0]?.message?.content || '无回应'
    
    console.log(`⏱️ 耗时: ${duration}ms`)
    console.log(`📊 Token使用: ${response.usage.prompt_tokens}输入 + ${response.usage.completion_tokens}输出 = ${response.usage.total_tokens}总计`)
    
    // 计算成本
    const currentProvider = aiService.getCurrentProvider()!
    const cost = aiService.calculateTokenCost(
      currentProvider, 
      model,
      response.usage.prompt_tokens,
      response.usage.completion_tokens
    )
    console.log(`💰 预估成本: $${cost.toFixed(6)}`)
    
    console.log(`📝 回答内容:`)
    console.log(content)
    console.log('\n' + '='.repeat(80))
    
    return {
      success: true,
      duration,
      usage: response.usage,
      cost,
      content: content.length
    }
    
  } catch (error) {
    console.error(`❌ 测试失败:`, error)
    return {
      success: false,
      error: error instanceof Error ? error.message : String(error)
    }
  }
}

// 执行完整测试套件
export async function runModelComparison() {
  console.log('🚀 开始测试最新AI模型...')
  console.log('测试模型:')
  console.log('- Qwen Plus Latest (深度思考)')
  console.log('- Doubao Seed 1.6')  
  console.log('- DeepSeek Reasoner (推理模型)')
  console.log('\n' + '='.repeat(80))

  // 检查API密钥状态
  const status = aiService.getProviderStatus()
  console.log('📋 API密钥状态:')
  Object.entries(status).forEach(([provider, info]) => {
    console.log(`- ${provider}: ${info.hasApiKey ? '✅ 已配置' : '❌ 未配置'}`)
  })
  
  if (!status.qwen.hasApiKey || !status.doubao.hasApiKey || !status.deepseek.hasApiKey) {
    console.log('\n⚠️ 请确保所有API密钥都已配置在.env文件中')
    return
  }

  const models = [
    { provider: 'qwen', model: 'qwen-plus-latest', name: 'Qwen Plus Latest' },
    { provider: 'doubao', model: 'doubao-seed-1-6-250615', name: 'Doubao Seed 1.6' },
    { provider: 'deepseek', model: 'deepseek-reasoner', name: 'DeepSeek Reasoner' }
  ]

  const results: Record<string, any[]> = {}

  // 为每个模型执行所有测试任务
  for (const { provider, model, name } of models) {
    console.log(`\n🔄 开始测试 ${name}...`)
    results[name] = []
    
    for (const task of TEST_TASKS) {
      const result = await runSingleTest(task, provider, model)
      results[name].push({ task: task.name, ...result })
      
      // 测试间隔，避免请求过快
      await new Promise(resolve => setTimeout(resolve, 1000))
    }
  }

  // 生成对比报告
  generateComparisonReport(results)
}

// 生成对比报告
function generateComparisonReport(results: Record<string, any[]>) {
  console.log('\n📊 模型对比报告')
  console.log('='.repeat(80))

  // 成功率统计
  console.log('\n✅ 成功率统计:')
  Object.entries(results).forEach(([model, tasks]) => {
    const successCount = tasks.filter(t => t.success).length
    const successRate = (successCount / tasks.length * 100).toFixed(1)
    console.log(`${model}: ${successCount}/${tasks.length} (${successRate}%)`)
  })

  // 平均响应时间
  console.log('\n⏱️ 平均响应时间:')
  Object.entries(results).forEach(([model, tasks]) => {
    const successfulTasks = tasks.filter(t => t.success && t.duration)
    if (successfulTasks.length > 0) {
      const avgDuration = successfulTasks.reduce((sum, t) => sum + t.duration, 0) / successfulTasks.length
      console.log(`${model}: ${avgDuration.toFixed(0)}ms`)
    }
  })

  // 平均成本
  console.log('\n💰 平均成本:')
  Object.entries(results).forEach(([model, tasks]) => {
    const successfulTasks = tasks.filter(t => t.success && t.cost !== undefined)
    if (successfulTasks.length > 0) {
      const avgCost = successfulTasks.reduce((sum, t) => sum + t.cost, 0) / successfulTasks.length
      console.log(`${model}: $${avgCost.toFixed(6)}`)
    }
  })

  // Token使用统计
  console.log('\n📈 平均Token使用:')
  Object.entries(results).forEach(([model, tasks]) => {
    const successfulTasks = tasks.filter(t => t.success && t.usage)
    if (successfulTasks.length > 0) {
      const avgInputTokens = successfulTasks.reduce((sum, t) => sum + t.usage.prompt_tokens, 0) / successfulTasks.length
      const avgOutputTokens = successfulTasks.reduce((sum, t) => sum + t.usage.completion_tokens, 0) / successfulTasks.length
      console.log(`${model}: ${avgInputTokens.toFixed(0)}输入 + ${avgOutputTokens.toFixed(0)}输出`)
    }
  })

  console.log('\n🎯 测试总结:')
  console.log('- Qwen Plus Latest: 支持深度思考，适合复杂推理任务')
  console.log('- Doubao Seed 1.6: 新一代种子模型，理解生成能力强')
  console.log('- DeepSeek R1: 专业推理模型，逻辑思维能力突出')
  console.log('\n建议根据具体任务类型选择最适合的模型。')
}

// 快速测试函数
export async function quickTest() {
  console.log('🔥 快速测试三个模型...')
  
  const testPrompt = '请解释一下量子计算的基本原理，用通俗易懂的语言。'
  
  const models = [
    { provider: 'qwen', model: 'qwen-plus-latest', name: 'Qwen Plus Latest' },
    { provider: 'doubao', model: 'doubao-seed-1-6-250615', name: 'Doubao Seed 1.6' },
    { provider: 'deepseek', model: 'deepseek-reasoner', name: 'DeepSeek Reasoner' }
  ]

  for (const { provider, model, name } of models) {
    console.log(`\n--- ${name} ---`)
    try {
      const startTime = Date.now()
      const response = await aiService.quickChat(testPrompt, '你是一个科学普及专家', {
        provider,
        model
      })
      const duration = Date.now() - startTime
      console.log(`⏱️ 响应时间: ${duration}ms`)
      console.log(`📝 回答: ${response.substring(0, 200)}...`)
    } catch (error) {
      console.error(`❌ 失败:`, error)
    }
  }
}

// 如果直接运行此文件，执行快速测试
if (typeof window === 'undefined') {
  quickTest().catch(console.error)
}